package org.esti.model.dao.impl;

import org.esti.model.Level;
import org.esti.model.dao.LevelDAO;
import org.esti.model.exceptions.LevelDoesNotExistException;
import org.springframework.stereotype.Repository;

import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import java.util.List;

/**
 * @author Artem Loginov (logart)
 */
@Repository
public class LevelDAOimpl implements LevelDAO {

    @PersistenceContext
    private EntityManager entityManager;

    /**
     * {@inheritDoc}
     */
    @Override
    public List<Level> getAllLevels() {
        Query query = entityManager.createQuery("FROM Level");
        return query.getResultList();

    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Level get(Long id) {
        try {
            Query query = entityManager.createQuery("FROM Level WHERE id=:id");
            query.setParameter("id", id);
            return (Level) query.getSingleResult();
        } catch (NoResultException ex) {
            throw new LevelDoesNotExistException(ex);
        }
    }
}
